package com.sifa.springcloud.controller;

import com.sifa.springcloud.Ib.LoadBalancer;
import com.sifa.springcloud.entities.CommentResult;
import com.sifa.springcloud.entities.Payment;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
public class OrderController {
    public static  final String PAYMENT_URL="http://CLOUD-PAYMENT-SERVICE";
//    public static  final String PAYMENT_URL="http://localhost:8001";
    @Resource
    private LoadBalancer loadBalancer;
    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
  private RestTemplate restTemplate;
    @GetMapping("/customer/payment/create")
    public CommentResult<Payment> createPayment(Payment payment){
      return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommentResult.class);
    }
    @GetMapping("/customer/payment/get/{id}")
    public CommentResult<Payment> getPayment(@PathVariable("id") Integer id){
     return   restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommentResult.class);
    }

    @GetMapping("/customer/payment/getEntity/{id}")
    public CommentResult<Payment> getPayment2(@PathVariable("id")Integer id){
        ResponseEntity<CommentResult> entity = restTemplate.getForEntity(PAYMENT_URL + "payment/get/" + id, CommentResult.class);

          if (entity.getStatusCode().is2xxSuccessful()){
              return  entity.getBody();//getBody就是获取entity中的那个对象
          }else {
              return new CommentResult<>(404,"操作失败");
          }
    }
    @GetMapping("consumer/payment/lb")
    public String getPaymentUrl(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances==null||instances.size()<=0){
            return null;
        }
        ServiceInstance serviceInstance=loadBalancer.instance(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri+"payment/lb",String.class);
    }
}
